<template>
    <div class="e-form">
        <BillTop title="操作手登记编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
            <el-tab-pane label="考核记录" name="records" :disabled="clickTabFlag"></el-tab-pane>
            <el-tab-pane label="工作经历" name="workExperience" :disabled="clickTabFlag"></el-tab-pane>
            <el-tab-pane label="证书信息" name="information" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.operator" label-width="150px" :rules="rules" >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="来源：" prop="source">
                                            <el-select
                                                v-model="formData.operator.source"
                                                @change="sourceChange"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="(
                                                        item, index
                                                    ) in ['外部','内部']"
                                                    :key="index"
                                                    :label="item"
                                                    :value="index"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="姓名：" prop="operator">
                                            <el-input v-model="formData.operator.operator" :readonly="isNameSelect">
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy"  @click="selectName" v-if="isNameSelect"></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="联系电话：" prop="phoneNo">
                                            <el-input v-model="formData.operator.phoneNo" maxlength="11"
                                            v-enter-number="{
                                                set: formData,
                                                val: 'operator',
                                                key: 'phoneNo'
                                            }">
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="身份证号：" prop="idCard">
                                            <el-input v-model="formData.operator.idCard" :readonly="isNameSelect" @blur="getgender">
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="性别：" prop="gender">
                                            <el-radio-group v-model="formData.operator.gender" :disabled="isNameSelect">
                                                <el-radio :label="0">女</el-radio>
                                                <el-radio :label="1">男</el-radio>
                                            </el-radio-group>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="工作状态：" prop="workState">
                                            <el-select
                                                v-model.number="formData.operator.workState"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="(
                                                        item, index
                                                    ) in workStatus"
                                                    :key="index"
                                                    :label="item.label"
                                                    :value="Number(item.value)"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="入场时间：" prop="enterDate">
                                            <el-date-picker
                                                v-model="formData.operator.enterDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="离场时间：" prop="exitDate">
                                            <el-date-picker
                                                v-model="formData.operator.exitDate"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                    <el-form-item label="操作范围：" prop="operatingRange">
                                            <span> {{ formData.operator.operatingRange }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="共享：">
                                            <el-checkbox v-model="formData.operator.isShared"></el-checkbox>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="考评等级：">
                                            <el-select
                                                v-model="formData.operator.assessmentLevel"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="(
                                                        item, index
                                                    ) in assessmentLevel"
                                                    :key="index"
                                                    :label="item"
                                                    :value="index"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="登录机构：">
                                            <span> {{formData.operator.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item  label="考评内容：">
                                        <el-input type="textarea" v-model="formData.operator.assessmentContent" placeholder="请输入内容"></el-input>
                                    </el-form-item>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="recordsCon" class="con">
                        <div class="tabs-title" id="records">考核记录</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                :data="formData.operatorAssessment"
                                border
                                ref="records"
                                v-sortTable="{ 'tableData': formData.operatorAssessment, '_this': this, 'ref': 'records' }"
                            >
                                <el-table-column
                                    prop="assessmentContent"
                                    align="center"
                                    min-width="200"
                                    show-overflow-tooltip
                                    label="考评内容"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="assessmentLevel"
                                    label="考评等级"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ assessmentLevel[row.assessmentLevel] }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="操作机构"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="recorder"
                                    label="操作人"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="source"
                                    label="来源"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{['PCWP','智慧管理平台'][row.source]}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="workExperienceCon" class="con">
                        <div class="tabs-title" id="workExperience">工作经历</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button  class="btn-greenYellow" @click="addWorkExperience">新增</el-button>
                                        <el-button  class="btn-delete" @click="deleteOperatorWorkExperience" v-if="isBatch[0].flag">批量删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('workExperience')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[0].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorWorkMsg.length>0">
                                <span v-for="item,index in errorWorkMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="workSelect"
                                :data="operatorWorkExperienceCopy"
                                border
                                @selection-change="workTableSelect"
                                v-sortTable="{ 'tableData': operatorWorkExperienceCopy, '_this': this, 'ref': 'workSelect' }"
                            >
                                <el-table-column type="selection" align="center" width="55" v-if="isBatch[0].flag"></el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDeleteWork(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="corporateName"
                                    label="单位名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.corporateName" clearable @input="rowCurWorkChangeTable(row)"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="operatingRange"
                                    label="操作范围"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.operatingRange" readonly @input="rowCurWorkChangeTable(row)">
                                            <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectRange(row)"></i>
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="startDate"
                                    label="开始时间"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker
                                            v-model="row.startDate"
                                            type="date"
                                            placeholder="选择日期"
                                            :clearable="false"
                                            value-format="yyyy-MM-dd"
                                            @input="rowCurWorkChangeTable(row)"
                                        >
                                        </el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="endDate"
                                    label="结束时间"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker
                                            v-model="row.endDate"
                                            type="date"
                                            placeholder="选择日期"
                                            :clearable="false"
                                            value-format="yyyy-MM-dd"
                                            @input="rowCurWorkChangeTable(row)"
                                        >
                                        </el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="source"
                                    label="来源"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{['系统外','系统内'][row.source] }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="informationCon" class="con">
                        <div class="tabs-title" id="information">证书信息</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div style="padding-right:8px">
                                        <el-upload
                                            v-if="formData.operatorCertificate.length>0"
                                            class="upload-demo"
                                            :action="uploadUrl"
                                            :headers="{
                                                token: userInfo.token,
                                                org: encodeURIComponent(JSON.stringify(userInfo.orgInfo))
                                            }"
                                            :data="{
                                                bucketName,
                                                relationId,
                                                orgCode
                                            }"
                                            :before-upload="beforeAvatarUpload"
                                            multiple
                                            :accept="accept"
                                            :on-success="attachOnSuccess"
                                            :http-request="uploadBefore"
                                            :show-file-list="false"
                                            name="files"
                                        >
                                            <el-button class="btn-greenYellow">
                                                上传附件
                                            </el-button>
                                        </el-upload>
                                    </div>
                                    <div>
                                        <el-button  class="btn-greenYellow" v-if="isBatch[1].flag" @click="attachDownload">批量下载</el-button>
                                        <el-button  class="btn-delete" v-if="isBatch[1].flag" @click="handleBatchDelFile">批量删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('information')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[1].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorFileMsg.length>0">
                                <span v-for="item,index in errorFileMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="information"
                                :data="operatorCertificateCopy"
                                @selection-change="fileTableSelect"
                                border
                                v-sortTable="{ 'tableData': operatorCertificateCopy, '_this': this, 'ref': 'information' }"
                            >
                                <el-table-column type="selection" align="center" width="55" v-if="isBatch[1].flag"></el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDeleteFile(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="operatingRange"
                                    label="操作范围"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.operatingRange" readonly @input="fileCurRowChangeType(row)">
                                            <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectRangeInfo(row)"></i>
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="certificationAuthority"
                                    label="发证机关"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.certificationAuthority" @input="fileCurRowChangeType(row)">
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="issueDate"
                                    label="发证日期"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker
                                            v-model="row.issueDate"
                                            type="date"
                                            placeholder="选择日期"
                                            value-format="yyyy-MM-dd"
                                            @input="fileCurRowChangeType(row)"
                                            :clearable="false"
                                        >
                                        </el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="annualReview"
                                    label="年审日期"
                                    width="160"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker
                                            v-model="row.annualReview"
                                            type="date"
                                            placeholder="选择日期"
                                            value-format="yyyy-MM-dd"
                                            @input="fileCurRowChangeType(row)"
                                            :clearable="false"
                                        >
                                        </el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="filePath" width="200" label="缩略图">
                                    <template slot-scope="{ row }" :size="50">
                                        <div style="display: flex; justify-content: center;">
                                            <el-image
                                                v-if="'jpg,jpeg,png'.includes(row.fileName.split('.').pop().toLowerCase())"
                                                style="width: 60px; height: 45px"
                                                :src="oss + row.nonIPObjectPath"
                                                :preview-src-list="imageList"
                                            ></el-image>
                                            <el-image v-else style="width: 60px; height: 45px" :src="pdfImg"></el-image>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="fileName"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                    label="文件名称"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="fileSize"
                                    label="文件大小"
                                    width="100"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        {{ row.fileSize ? bytesToSize(row.fileSize) : '' }}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="uploaderDate"
                                    label="上传时间"
                                    show-overflow-tooltip
                                    width="120"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="uploader"
                                    label="上传人"
                                    width="120"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <div class="upload" slot="empty">
                                    <el-upload
                                       class="upload-demo"
                                        drag
                                        :action="uploadUrl"
                                        :headers="{
                                            token: userInfo.token,
                                            org: encodeURIComponent(JSON.stringify(userInfo.orgInfo))
                                        }"
                                        :data="{
                                            bucketName,
                                            relationId,
                                            orgCode
                                        }"
                                        :before-upload="beforeAvatarUpload"
                                        multiple
                                        :accept="accept"
                                        :on-success="attachOnSuccess"
                                        :http-request="uploadBefore"
                                        :show-file-list="false"
                                        name="files"
                                    >
                                        <el-button type="primary" style="padding: 20px 80px">上传附件</el-button>
                                        <div style="margin-top: 10px; line-height: 25px; font-size: 12px">
                                            鼠标拖入上传，按住Ctrl可多选附件<br />
                                            *仅支持上传图片、PDF格式，文件小于20M
                                        </div>
                                    </el-upload>
                                </div>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                size="small"
                class="btn-blue"
                @click="preserve"
                v-debounce
                >保存</el-button
            >
            <el-button
                type="primary"
                size="small"
                class="btn-delete"
                @click="deleteBill"
                v-debounce
                >删除</el-button
            >
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/operatorManagement.js'
import '@/utils/jquery.scrollTo.min'
import { formatDate } from '@/utils/common.js'
import { isPhone, isIdcard } from '@/utils/rules'
//import { ip } from '@/utils/request'
import { oss } from '@/utils/request'
import { bytesToSize, selectDataClient, batchDownload } from '@/utils/common'
import ossRequest from '@/api/oss/oss.js'
import { selectEquipmentBase } from '@/api/equip/popupCallback.js'
import pdfImg from '@/assets/pdf_icon.png'
export default {
    data () {
        return {
            oss: oss,
            isBatch: [
                {
                    flag: true,
                    batch: '进入批量管理'
                },
                {
                    flag: true,
                    batch: '进入批量管理'
                }
            ],
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            selectEquipVisible: false,
            tableData: [],
            formData: {
                'operator': {
                    'assessmentContent': '',
                    'assessmentLevel': '',
                    'billId': '',
                    'enterDate': '',
                    'exitDate': '',
                    'founderId': '',
                    'founderName': '',
                    'gender': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'idCard': '',
                    'initial': '',
                    'isShared': true,
                    'isSynchronize': true,
                    'operatingRange': '',
                    'operator': '',
                    'orgId': '',
                    'orgName': '',
                    'phoneNo': '',
                    'recorder': '',
                    'recorderId': '',
                    'source': 0,
                    'workState': null
                },
                'operatorAssessment': [], //考核记录
                'operatorCertificate': [], //证书信息
                'operatorWorkExperience': [], //工作经历
                'state': 1
            },
            operatingRangeArr: [], //基本信息存操作范围
            operatorWorkExperienceCopy: [], //工作经历列表绑定
            workSelect: [], //工作经历选择项
            operatorCertificateCopy: [], //证书信息列表绑定
            fileSelect: [], //证书信息选择项
            currentRowWork: {}, //当前工作经历行数据
            currentRowFile: {}, //当前证书信息行数据
            billid: this.$route.query.billid,
            switchNum: 0,
            workIndex: 0, //工作经历的第几项选择设备
            rules: {
                source: [
                    { required: true, message: '请选择来源', trigger: 'change' },
                ],
                operator: [
                    { required: true, message: '请输入名字', trigger: 'change'  },
                ],
                phoneNo: [
                    { required: true, message: '请输入电话', trigger: ['blur', 'change'] },
                    { validator: isPhone, trigger: 'blur' }
                ],
                idCard: [
                    { required: true, message: '请输入身份证', trigger: ['blur', 'change'] },
                    { validator: isIdcard, trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: ['blur', 'change'] },
                ],
                workState: [
                    { required: true, message: '请选择工作状态', trigger: 'change' },
                ],
                enterDate: [
                    { required: false, validator: (rule, value, callback)=>{
                        if (this.formData.operator.exitDate) {
                            const enterDate = new Date(this.formData.operator.enterDate).getTime() //入场时间
                            const exitDate = new Date(this.formData.operator.exitDate).getTime() //离场时间
                            if(enterDate > exitDate) {
                                callback(new Error('入场时间不能大于离场时间'))
                            }else{
                                callback()
                            }
                        }else{
                            callback()
                        }
                    }, trigger: ['blur', 'change'] }
                ],
                exitDate: [
                    { required: false, validator: (rule, value, callback)=>{
                        if (this.formData.operator.enterDate) {
                            const enterDate = new Date(this.formData.operator.enterDate).getTime() //入场时间
                            const exitDate = new Date(this.formData.operator.exitDate).getTime() //离场时间
                            if(enterDate > exitDate) {
                                callback(new Error('离场时间不能小于入场时间'))
                            }else{
                                callback()
                            }
                        }else{
                            callback()
                        }
                    }, trigger: ['blur', 'change'] }
                ],
            },
            errorList: [], //控制导航栏感叹号的显示
            errorWorkMsg: [], //工作经验错误显示
            errorFileMsg: [], //证书信息错误显示
            uploadUrl: 'oss/uploader',
            accept: '.jpg,jpesg,.png,.pdf',
            pdfImg,
            relationId: '',
            isNameSelect: false,
            oldSource: '',
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            workStatus: state=>state.equip.equipData.workStatus,
            assessmentLevel: state=>state.equip.equipData.assessmentLevel,
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        },
        bucketName () {
            return 'facilitybase'
        },
        imageList () {
            return this.operatorCertificateCopy.filter(row=>'jpg,jpeg,png'.includes(row.fileName.split('.').pop().toLowerCase())).map(x=>oss + x.nonIPObjectPath)
        }
    },
    components: {
    },
    created () {
        this.getBillId()
        this.userId = localStorage.getItem('userId')
    },
    mounted () {
        if(this.billid) {
            this.getInfo()
        }
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'records', 'workExperience', 'information']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })

    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        //获取切换来源前的值
        'formData.operator.source': function (newVal, oldVal) {
            this.oldSource = oldVal
        },
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //前端生成billid
        getBillId () {
            this.formData.operator.orgName = this.userInfo.orgInfo.orgName
            request.getBillId().then(res=>{
                this.formData.operator.billId = res[0]
                // this.relationId = res[0]
            })
        },
        batchOperation (name) {
            switch(name) {
            case 'workExperience':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch[0].flag) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.workSelect.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'information':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if(this.isBatch[1].flag) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.information.clearSelection()
                }else{
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            }

        },
        //输入身份证判断性别
        getgender () {
            let isEven = this.formData.operator.idCard.charAt(16)
            this.formData.operator.gender = isEven % 2 == 0 ? 0 : 1
        },
        //来源选择
        sourceChange (val) {
            this.isNameSelect = val == 0 ? false : true
            this.clientPop(
                'info',
                '切换来源数据将被清空，是否继续?',
                ()=>{
                    this.operatorWorkExperienceCopy = [] //工作经历
                    this.operatorCertificateCopy = [] //证书信息
                    this.formData.operator = {
                        'assessmentContent': '',
                        'assessmentLevel': '',
                        'billId': '',
                        'enterDate': '',
                        'exitDate': '',
                        'founderId': '',
                        'founderName': '',
                        'gender': '',
                        'gmtCreate': '',
                        'gmtModified': '',
                        'idCard': '',
                        'initial': '',
                        'isShared': true,
                        'isSynchronize': true,
                        'operatingRange': '',
                        'operator': '',
                        'orgId': '',
                        'orgName': '',
                        'phoneNo': '',
                        'recorder': '',
                        'recorderId': '',
                        'source': val,
                        'workState': null
                    }
                    if(this.billid) {
                        this.formData.operator.billId = this.billid
                    }else{
                        this.getBillId()
                    }
                    //考核记录
                    this.formData.operatorAssessment.forEach(item=>{
                        item.changeType = -1
                    })
                    //证书信息
                    this.formData.operatorCertificate.forEach(item=>{
                        item.changeType = -1
                    })
                    //工作经历
                    this.formData.operatorWorkExperience.forEach(item=>{
                        item.changeType = -1
                    })
                    this.formData.state = 0 //0修改 1 新增
                },
                null,
                ()=>{
                    this.formData.operator.source = this.oldSource
                }
            )
        },
        //弹窗选择名字
        selectName () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/user/getUserUnderOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                Title: '人员选择' // 标题
            }).then(val => {
                this.setSelectedInfo(val)
                request.getUserInfo(val[0].userId).then(res=>{
                    this.formData.operator.operator = res.userName
                    this.formData.operator.phoneNo = res.phoneNo
                    this.formData.operator.gender = res.gender
                    this.formData.operator.idCard = res.idNo
                })
            })
        },
        //获取操作手信息
        getInfo () {
            request.operatorInfo(this.billid).then(res=>{
                this.operatorWorkExperienceCopy = []
                this.operatorCertificateCopy = []
                res.operator.assessmentLevel = res.operator.assessmentLevel == -1 ? null : res.operator.assessmentLevel
                this.formData = res
                res.operatorWorkExperience.map(item=>{
                    this.operatorWorkExperienceCopy.push(item)
                })
                res.operatorCertificate.map(item=>{
                    this.operatorCertificateCopy.push(item)
                })
            })
        },
        //工作经历新增
        addWorkExperience () {
            const arr = this.formData.operatorWorkExperience ? this.formData.operatorWorkExperience : []
            let date  = formatDate(new Date(), 'yyyy-MM-dd')
            const obj = {
                'billId': '',
                'changeType': 1,
                'corporateName': '',
                'endDate': '',
                'gmtCreate': '',
                'gmtModified': '',
                'isGenerate': '',
                'operatingRange': '',
                'source': 0,
                'startDate': '',
                'workExperienceId': ''
            }
            obj.startDate = date
            obj.endDate = date
            arr.push(obj)
            this.operatorWorkExperienceCopy.push(obj)
            this.$set(this.formData, 'operatorWorkExperience',  arr)
        },
        //工作经历选择操作范围
        selectRange (row) {
            let arr = []
            let json = {
                'categoryId': '00000',
                'isUpdate': false,
                'keyword': ''
            }
            selectEquipmentBase(json).then(res=>{
                res.forEach(item=>{
                    arr.push(item.equipmentName)
                })
                row.operatingRange = arr.join(',')
                if (row.workExperienceId) {
                    row.changeType = 2
                }
            })
        },
        //判断当前状态是否修改
        rowCurWorkChangeTable (row) {
            this.currentRowWork = row
            if (row.workExperienceId) {
                this.currentRowWork.changeType = 2
            }
        },
        //单个删除
        handleDeleteWork (row, $index) {
            let length = this.errorWorkMsg.length
            if(row.source == 1) {
                this.clientPop(
                    'err',
                    '系统内工作经历无法删除！',
                )
            }else{
                this.clientPop(
                    'info',
                    this.oneDeleteErr(length),
                    ()=>{
                        if(row.workExperienceId) {
                            this.$set(this.formData.operatorWorkExperience[$index], 'changeType', -1)
                            this.operatorWorkExperienceCopy.splice($index, 1)
                            if (length > 0 ) {
                                this.verifyTable()
                            }
                        }else{
                            this.formData.operatorWorkExperience.splice($index, 1)
                            this.operatorWorkExperienceCopy.splice($index, 1)
                            if (length > 0 ) {
                                this.verifyTable()
                            }
                        }
                    }
                )
            }
        },
        //获取工作经历表格的选择项
        workTableSelect (selection) {
            this.workSelect = selection
        },
        //批量删除工作经历
        deleteOperatorWorkExperience () {
            const length = this.workSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.delete
                )
            }
        },
        delete () {
            let length = this.errorWorkMsg.length
            if (this.workSelect.length > 0) {
                this.workSelect.forEach(item=>{
                    if(item.workExperienceId) {
                        if(item.source !== 1) {
                            this.$set(item, 'changeType', -1)
                            for(let i = this.operatorWorkExperienceCopy.length; i > 0; i--) {
                                if(this.operatorWorkExperienceCopy[i - 1] === item) {
                                    this.operatorWorkExperienceCopy.splice(i - 1, 1)
                                }
                            }
                            if (length > 0 ) {
                                this.verifyTable()
                            }
                            this.$refs.workSelect.clearSelection()
                        }
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.formData.operatorWorkExperience.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.formData.operatorWorkExperience[i - 1] === localArr[j]) {
                                    this.formData.operatorWorkExperience.splice(i - 1, 1)
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                                if(this.operatorWorkExperienceCopy[i - 1] === localArr[j]) {
                                    this.operatorWorkExperienceCopy.splice(i - 1, 1)
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                            }
                        }
                        this.$refs.workSelect.clearSelection()
                    }
                })
            }
        },
        //验证工作经验表格
        verifyWork () {
            return  new Promise((resolve, reject)=>{
                this.errorWorkMsg = []
                this.operatorWorkExperienceCopy.forEach((item, index)=>{
                    if(item.endDate != '' || item.endDate != null) {
                        const startDate = new Date(item.startDate).getTime() //开始时间
                        const endDate = new Date(item.endDate).getTime() //结束时间
                        if(startDate > endDate) {
                            let str = `第 ${index + 1} 行的（结束时间不能小于开始时间）`
                            this.errorWorkMsg.push(str)
                        }
                    }
                })
                if(this.errorWorkMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                }else{
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        //证书信息
        //文件大小
        bytesToSize (byte) {
            return bytesToSize(byte)
        },
        //文件大小  文件上传之前判断大小不能超过20MB
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBefore (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccess()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error)
                })
        },
        //获取上传的对象
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest.getObjectByRelationId({ relationId: this.relationId }).then(res => {
                res.map(x => {
                    x.fileName = x.originalObjectName
                    x.fileSize = x.objectSize
                    x.uploader = x.ossBucketName
                    x.uploaderDate = x.gmtCreate
                    x.filePath = x.objectPath
                    return scrollX
                })
                let obj =  {
                    'annualReview': '',
                    'billId': '',
                    'certificateId': this.relationId,
                    'certificationAuthority': '',
                    'changeType': 1,
                    'fileName': '',
                    'filePath': '',
                    'fileSize': 0,
                    'gmtCreate': '',
                    'gmtModified': '',
                    'issueDate': '',
                    'operatingRange': '',
                    'uploader': '',
                    'uploaderId': '',
                    'uploaderDate': '',
                    'nonIPObjectPath': '', //不含IP/域名的对象路径  图片显示
                    ...res[0]
                }
                this.operatorCertificateCopy.push(obj)
                this.formData.operatorCertificate.push(obj)
            })
        },
        //上传成功
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        //判断当前状态是否修改
        fileCurRowChangeType (row) {
            this.currentRowFile = row
            if (row.billId) {
                this.currentRowFile.changeType = 2
            }
        },
        //证书信息选择操作手范围
        selectRangeInfo (row) {
            let arr = []
            let json = {
                'categoryId': '00000',
                'isUpdate': false,
                'keyword': ''
            }
            // selectDataClient({
            //     SelectServiceToken: '/facilitybase/equipment/getEquipmentCategoryAll', // 客户端对应方法名
            //     IsSingleMode: false, // 是否单选 true 单选 false 多选
            //     SelectedIDs: ['1502126658530504706'], // 已选中id
            //     InitParamsStr: JSON.stringify(json),    // 接口参数
            //     Title: '设备基础库' // 标题
            // }).then(val => {
            //     this.res = val
            // })
            selectEquipmentBase(json).then(res=>{
                res.forEach(item=>{
                    arr.push(item.equipmentName)
                })
                row.operatingRange = arr.join(',')
                this.formData.operator.operatingRange = row.operatingRange
                if (row.certificateId) {
                    this.currentRowFile.changeType = 2
                }
            })
        },
        //证书信息选中的行
        fileTableSelect (selection) {
            this.fileSelect = selection
        },
        //单个删除证书信息
        handleDeleteFile (row, $index) {
            let length = this.errorWorkMsg.length
            if(row.certificateId) {
                this.clientPop('info',  this.oneDeleteErr, ()=>{
                    this.$set(this.formData.operatorCertificate[$index], 'changeType', -1)
                    this.operatorCertificateCopy.splice($index, 1)
                    if (length > 0 ) {
                        this.verifyTable()
                    }
                    this.getOperatingRange()
                })
            }else{
                this.formData.operatorCertificate.splice($index, 1)
                this.operatorCertificateCopy.splice($index, 1)
                if (length > 0 ) {
                    this.verifyTable()
                }
                this.getOperatingRange()
            }
        },
        //批量删除证书信息
        handleBatchDelFile () {
            const length = this.fileSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.deleteFile
                )
            }
        },
        deleteFile () {
            let length = this.errorFileMsg.length
            this.fileSelect.filter(item => {
                // 如果有id ，则改changeType为-1
                if(item.certificateId) {
                    item.changeType = -1
                    this.operatorCertificateCopy.map((x, index)=>{
                        if(item == x ) {
                            this.operatorCertificateCopy.splice(index, 1)
                        }
                    })
                    if (length > 0 ) {
                        this.verifyTable()
                    }
                    this.getOperatingRange()
                }else{
                    this.formData.operatorCertificate.map((x, index)=>{
                        if(item == x ) {
                            this.formData.operatorCertificate.splice(index, 1)
                        }
                    })
                    this.operatorCertificateCopy.map((x, index)=>{
                        if(item == x ) {
                            this.operatorCertificateCopy.splice(index, 1)
                        }
                    })
                    if (length > 0 ) {
                        this.verifyTable()
                    }
                    this.getOperatingRange()
                }
            })
        },
        //批量下载
        attachDownload () {
            const length = this.fileSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '请选择要下载的数据！',
                )
                return
            }
            const fileList = this.fileSelect.map(item=>{
                return {
                    objectName: item.fileName,
                    objectPath: item.filePath
                }
            })
            batchDownload(fileList)
        },
        //验证证书信息表格
        verifyFile () {
            return  new Promise((resolve, reject)=>{
                this.errorFileMsg = []
                if(this.operatorCertificateCopy.length == 0) {
                    let str = '证书信息不能为空'
                    this.errorFileMsg.push(str)
                }
                this.operatorCertificateCopy.forEach((item, index)=>{
                    if(item.operatingRange == '' || item.operatingRange == null) {
                        let str = `第 ${index + 1} 行的（操作范围）不能为空`
                        this.errorFileMsg.push(str)
                    }
                    if(item.certificationAuthority == '' || item.certificationAuthority == null) {
                        let str = `第 ${index + 1} 行的（发证机关）不能为空`
                        this.errorFileMsg.push(str)
                    }
                    if(item.issueDate == '' || item.issueDate == null) {
                        let str = `第 ${index + 1} 行的（发证日期）不能为空`
                        this.errorFileMsg.push(str)
                    }
                    if(item.annualReview == '' || item.annualReview == null) {
                        let str = `第 ${index + 1} 行的（年审时间）不能为空`
                        this.errorFileMsg.push(str)
                    }
                })
                if(this.errorFileMsg.length > 0) {
                    this.isErrorFileMsg = true
                    reject()
                }else{
                    this.isErrorFileMsg = false
                    resolve()
                }
            })
        },
        //保存
        preserve () {
            return new Promise((resolve, reject)=>{
                //存在billid 0 修改 1 新增
                this.formData.state = this.billid ? 0 : 1
                this.$refs.form.validate(valid => {
                    if (valid) {
                        this.verifyWork().then(()=>{
                            this.verifyFile().then(()=>{
                                request.operatorAdd(this.formData).then(()=>{
                                    resolve()
                                    this.clientPop('suc', '保存成功', this.handleClose)
                                }).catch(err=>{
                                    reject(err)
                                })
                            }).catch(err=>{
                                reject(err)
                                this.setError('information')
                                this.scorllError()
                            })

                        }).catch(err=>{
                            reject(err)
                            this.setError('workExperience')
                            this.scorllError()
                        })
                    }else{
                        reject()
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //删除单据
        deleteBill () {
            this.clientPop('info', this.oneDeleteErr, ()=>{
                request.operatorDelete({ operatorIdList: this.billid }).then(()=>{
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/operatorList')
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
